package main

import (
	"context"
	"encoding/json"
	"github.com/micro/go-micro/config/cmd"
	"github.com/micro/go-micro/v2"
	authapi "github.com/micro/go-micro/v2/api/proto"
	"github.com/micro/go-micro/v2/auth"
	authservice "github.com/micro/go-micro/v2/auth/service"
	"github.com/micro/go-micro/v2/util/log"
	_ "github.com/micro/go-plugins/registry/eureka/v2"
	uaa "github.com/morphyguo/demo/api/uaa/proto"
	"github.com/morphyguo/demo/commons"
)

var _ uaa.AuthApiHandler = (*authproxy)(nil)

type authproxy struct {
	cl auth.Auth
}

func (a *authproxy) Login(ctx context.Context, in *authapi.Request, out *authapi.Response) error {
	req := &uaa.LoginRequest{}
	_ = json.Unmarshal([]byte(in.GetBody()), req)
	if tokens, err := a.cl.Token(auth.WithCredentials(req.Id, req.Secret)); err != nil {
		log.Warn("Login ", req.Id, ", secret = ", req.Secret, ", error ", err)
		return err
	} else {
		res := uaa.LoginResponse{
			Id:    req.Id,
			Token: tokens.AccessToken,
		}
		b, _ := json.Marshal(res)
		out.Body = string(b)
		out.Header = make(map[string]*authapi.Pair)
		out.Header["Cookie"] = &authapi.Pair{
			Key:    "Set-Cookie",
			Values: []string{"access_token="+res.Token},
		}
		return nil
	}
}

func (a *authproxy) RefreshToken(ctx context.Context, in *authapi.Request, out *authapi.Response) error {
	return nil
}

func (a *authproxy) Register(ctx context.Context, in *authapi.Request, out *authapi.Response) error {
	req := &uaa.RegisterRequest{}
	_ = json.Unmarshal([]byte(in.GetBody()), req)
	if g, err := a.cl.Generate(req.Id, auth.WithSecret(req.Secret), auth.WithRoles("admin"), auth.WithNamespace("go.micro")); err != nil {
		log.Warn("Register error", err)
		return err
	} else {
		log.Info("account= %v", g)
		res := uaa.RegisterResponse{
			Id: req.Id,
		}
		b, _ := json.Marshal(res)
		out.Body = string(b)
		return nil
	}
}

func main() {
	s := micro.NewService(micro.Name(commons.NsApiAuth),
	)
	s.Init()
	cmd.DefaultClients

	//cl := pb.NewAuthService(commons.NsSrvAuth, s.Client())

	if err := uaa.RegisterAuthApiHandler(s.Server(), &authproxy{authservice.NewAuth(auth.Namespace("go.micro"))}); err != nil {
		log.Fatal("RegisterAuthApiHandler fail ", err)
	}

	if err:= s.Run(); err != nil {
		log.Fatal("Run fail ", err)
	}
}
